<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/20
 * Time: 15:35
 */

namespace Lib\Utils;


class PayUtils
{
    /**
     * 签名  生成签名串  基于sha1withRSA
     * @param string $data 签名前的字符串
     * @return string 签名串
     */
    public static function sign($data) {
        $certs = array();
        $merchant_cert = C('__PAYPWD__');   //密钥
        openssl_pkcs12_read(file_get_contents($merchant_cert), $certs,"111111"); //其中password为你的证书密码
        if(!$certs) return ;
        $signature = '';
        openssl_sign($data, $signature, $certs['pkey']);
        return base64_encode($signature);
    }

    /**
     * 验证签名：
     * @param data：原文
     * @param signature：签名
     * @return bool 返回：签名结果，true为验签成功，false为验签失败
     */
    public static function verity($data,$signature)
    {
        $server_cert = C('__PAYKEY__');   //密钥
        $pubKey = file_get_contents($server_cert);
        $res = openssl_get_publickey($pubKey);
        $result = (bool)openssl_verify($data, base64_decode($signature), $res);
        openssl_free_key($res);
        return $result;
    }

    public static function getStrMsg($str) {
        /*****生成请求内容**开始*****/
        $strMD5 =  md5($str,true);
        $strsign =  PayUtils::sign($strMD5);
        $base64_src=base64_encode($str);
        $msg = $base64_src."|".$strsign;
        /*****生成请求内容**结束*****/
        return $msg;
    }


    public static function test_sign($data) {
        $certs = array();
        $merchant_cert = C('__PAYPWD__');   //密钥
        openssl_pkcs12_read(file_get_contents($merchant_cert), $certs,"111111"); //其中password为你的证书密码
        if(!$certs) return ;
        $signature = '';
        openssl_sign($data, $signature, $certs['pkey']);
        return base64_encode($signature);
    }

    public static function test_verity($data,$signature)
    {
        $server_cert = C('__PAYKEY__');   //密钥
        $pubKey = file_get_contents($server_cert);
        $res = openssl_get_publickey($pubKey);
        $result = (bool)openssl_verify($data, base64_decode($signature), $res);
        openssl_free_key($res);
        return $result;
    }

    public static function test_getStrMsg($str) {
        /*****生成请求内容**开始*****/
        $strMD5 =  md5($str,true);
        $strsign =  PayUtils::sign($strMD5);
        $base64_src=base64_encode($str);
        $msg = $base64_src."|".$strsign;
        /*****生成请求内容**结束*****/
        return $msg;
    }
}